//
//  PlayViewController.m
//  New
//
//  Created by dlios on 15-7-16.
//  Copyright (c) 2015年 yangTao. All rights reserved.
//

#import "PlayViewController.h"

@interface PlayViewController ()

@end

@implementation PlayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[playDataBase sharPlayDataBase]OpenDB];
    [[playDataBase sharPlayDataBase]creatTable];
    
    BaseLabel *title =[[BaseLabel alloc]initWithFrame:CGRectMake(WIDTH/2 - 60, 5, 120, 40)];
    title.backgroundColor = [UIColor clearColor];
    self.navigationItem.titleView =title;
    title.text = @"即时新闻";
    title.textAlignment = NSTextAlignmentCenter;
    title.font = [UIFont systemFontOfSize:20];
    
    
    self.timeLabel = [[BaseLabel alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 25)];
    self.timeLabel.backgroundColor = [UIColor lightGrayColor];
    self.timeLabel.alpha = 0.5;
    [self.view addSubview:self.timeLabel];
   
    
    //确定当前时间
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    

        NSString *string = [NSString stringWithFormat:@"%ld年%ld月%ld日          %02ld:%02ld:%02ld",[dateComponent year],[dateComponent month],[dateComponent day],[dateComponent hour],[dateComponent minute],[dateComponent second]];
        
        self.timeLabel.text = string;
        
        

    
    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    
       self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 25, WIDTH, HEIGHT - 22 - 44 - 49) style:UITableViewStylePlain];
    self.tableV.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableV];
  self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableV.dataSource = self;
    self.tableV.delegate = self;
    self.array = [NSMutableArray array];
    self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.MBHUD.labelText = @"正在加载中";
    [self.MBHUD show:YES];
    [self.tableV.header beginRefreshing];
    [self headerRefesh];
    [self footerRefesh];
    [self getInFo];
    // Do any additional setup after loading the view.
}

//下拉刷新
-(void)headerRefesh {
    self.tableV.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 1;
        self.downUpdata = YES;
        
        //让菊花旋转起来
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
        
        [self.tableV reloadData];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        
        
        
    }];
    
}
#warning 上拉加载
-(void)footerRefesh {
    
    self.tableV.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        
        self.nextPage++;
        self.downUpdata = NO;
        self.MBHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.MBHUD.labelText = @"正在加载中...";
        [self.MBHUD show:YES];
        [self getInFo];
        
        // 刷新表格
        [self.tableV reloadData];
        
    }];
    
}




-(void)getInFo{
    
    self.array = [[playDataBase sharPlayDataBase]selectAllplayMod];
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = [NSString stringWithFormat:@"http://api.wallstreetcn.com:80/v2/livenews?page=%ld&_eva_t=1437037328",self.nextPage];
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
//    NSLog(@"!!!!!!!!%@",responseObject);
        //如果是下拉
        if (self.nextPage == 1) {
            [[playDataBase sharPlayDataBase]dropTable];
            [[playDataBase sharPlayDataBase]creatTable];
            [self.array removeAllObjects];
            
        }

        NSMutableArray *array = [responseObject objectForKey:@"results"];
        for (NSMutableDictionary *dic in array) {
            PlayModel *play = [[PlayModel alloc]init];
            play.ID = [dic objectForKey:@"id"];
            play.title = [dic objectForKey:@"title"];
            play.contentHtml = [dic objectForKey:@"contentHtml"];
            play.node_color = [dic objectForKey:@"node_color"];
            [self.array addObject:play];
            
            [[playDataBase sharPlayDataBase]insertNewModel:play];
        }
        [self.tableV reloadData];
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tableV.footer endRefreshing];
        [self.tableV.header endRefreshing];
        [self.MBHUD hide:YES];

        
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
             // 拿到当前的下拉刷新控件，结束刷新状态
             [self.tableV.footer endRefreshing];
             [self.tableV.header endRefreshing];
             [self.MBHUD hide:YES];
             UIAlertView *alView = [[UIAlertView alloc]initWithTitle:@"网络不给力" message:@"确认您已连接到网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [alView show];
             
    }];
    
    




}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *indent = @"cell";
    self.cell = [tableView dequeueReusableCellWithIdentifier:indent];
    if (self.cell == nil) {
        self.cell = [[PlayTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indent];
    }
    self.cell.backgroundColor = [UIColor clearColor];
    self.cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.cell.play = [self.array objectAtIndex:indexPath.row];
    
  
    return self.cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

        self.cell.context.numberOfLines = 0;
        CGSize size = CGSizeMake(320, 2000);
        NSStringDrawingOptions option = NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading;
    
        //NSStringDrawingTruncatesLastVisibleLine如果文本内容超出指定的矩形限制，文本将被截去并在最后一个字符后加上省略号。 如果指定了NSStringDrawingUsesLineFragmentOrigin选项，则该选项被忽略 NSStringDrawingUsesFontLeading计算行高时使用行间距。（译者注：字体大小+行间距=行高）
    
        NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName];
    
        CGRect labelSize = [self.cell.context.text boundingRectWithSize:size options:option attributes:attributes context:nil];
    if (WIDTH > 375) {
        self.cell.context.frame = CGRectMake(40, 0, labelSize.size.width+50, labelSize.size.height+40);

    }
    
    if (WIDTH == 375) {
       self.cell.context.frame = CGRectMake(40, 0, labelSize.size.width+10, labelSize.size.height+40);
    }
    else if(WIDTH < 375) {
    self.cell.context.frame = CGRectMake(40, 0, labelSize.size.width - 50, labelSize.size.height+20);
    }
    
  self.cell.view.frame = CGRectMake(25, 0, 1, labelSize.size.height+20);
        //设置cell的高度
        

    
    return (labelSize.size.height + 20);

}

-(void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:YES];
    
    [self.tableV reloadData];

}


-(void)timeAction{
    //确定当前时间
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    
 
        NSString *string = [NSString stringWithFormat:@"%ld年%ld月%ld日          %02ld:%02ld:%02ld",[dateComponent year],[dateComponent month],[dateComponent day],[dateComponent hour],[dateComponent minute],[dateComponent second]];
        
        self.timeLabel.text = string;
        
   

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PlayDetailViewController *playDVC = [[PlayDetailViewController alloc]init];
    
    PlayModel *play = [self.array objectAtIndex:indexPath.row];
  playDVC.ID = play.ID;
    playDVC.contentHtml =play.contentHtml;
    [self.navigationController pushViewController:playDVC animated:YES];

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
